package com.plian.system.controller.qg.subsidiary;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.Tools.Func;
import com.plian.Tools.StringPool;
import com.plian.Tools.TokenUtil;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.config.Resubmit;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dto.qg.subsidiary.SubsidiaryMixedReformDTO;
import com.plian.system.entity.qg.subsidiary.SubsidiaryMixedReform;
import com.plian.system.enumeratea.ReformStatus;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.qg.subsidiary.ISubsidiaryMixedReformService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.qg.subsidiary.SubsidiaryMixedReformVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.wrapper.qg.subsidiary.SubsidiaryMixedReformWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 子企业混合所有制改革进展 控制器
 *
 * @author jianglei
 * @since 2019-11-05
 */
@RestController
@AllArgsConstructor
@RequestMapping("api/subsidiarymixedreform")
@Api(value = "混改登记信息表", tags = "混改登记信息表接口")
public class SubsidiaryMixedReformController extends BaseController {

    private ISubsidiaryMixedReformService subsidiaryMixedReformService;

    private FormWorkflowService formWorkflowService;

    private SubsidiaryMixedReformWrapper subsidiaryMixedReformWrapper;

    /**
     * 详情
     */
    @PostMapping("/detail")
    public R<SubsidiaryMixedReformVO> detail(@Valid @RequestBody SubsidiaryMixedReform subsidiaryMixedReform) {
        SubsidiaryMixedReform detail = subsidiaryMixedReformService.getOne(Condition.getQueryWrapper(subsidiaryMixedReform));
        SubsidiaryMixedReformVO subsidiaryMixedReformVO = subsidiaryMixedReformWrapper.entityToVO(detail);
        return subsidiaryMixedReformService.getDetailObj(subsidiaryMixedReformVO);
    }

    /**
     * 分页 子企业混合所有制改革进展
     */
    @PostMapping("/list")
    public ListResult<SubsidiaryMixedReformVO> list(@Valid @RequestBody Query query) {
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }

        List<SearchEntity> entityList = query.getSearch();
        QueryWrapper<SubsidiaryMixedReform> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new SubsidiaryMixedReform()), entityList
        );
        TokenSearch<SubsidiaryMixedReform> tokenSearch = new TokenSearch<>();
        tokenSearch.addTokenQuery(queryWrapper, query);
        queryWrapper.lambda().eq(SubsidiaryMixedReform::getFormType, String.valueOf(FormTypeConstant.QG_SUBSIDIARY_FORM));

        IPage<SubsidiaryMixedReform> pages = subsidiaryMixedReformService.page(Condition.getPage(query), queryWrapper);
        ListResult<SubsidiaryMixedReformVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(subsidiaryMixedReformWrapper.entityToVO((pages).getRecords()));
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }


    /**
     * 新增或修改 子企业混合所有制改革进展
     */
    @PostMapping("/submit")
    @LogOperation("混改登记信息-提交")
    @Resubmit(delaySeconds = 0)
    public R submit(@Valid @RequestBody SubsidiaryMixedReform subsidiaryMixedReform) {
        if (!(Optional.ofNullable(subsidiaryMixedReform).isPresent() && Optional.ofNullable(subsidiaryMixedReform.getStatus()).isPresent()
                && subsidiaryMixedReform.getStatus() == -1)) {
            R result = subsidiaryMixedReformService.checkSubmit(subsidiaryMixedReform);
            if (Optional.ofNullable(result).isPresent()) {
                return result;
            }
        }
        boolean result = subsidiaryMixedReformService.submit(subsidiaryMixedReform);
        HashMap<String, Object> processVariable = new HashMap<>();
        formWorkflowService.startProcessAndSimulate(String.valueOf(subsidiaryMixedReform.getId()), subsidiaryMixedReform.getFormType(), processVariable);

        return result ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }


    /**
     * 删除 子企业混合所有制改革进展
     */
    @PostMapping("/remove")
    @LogOperation("混改登记信息-删除")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>) pd.get("ids");
        return subsidiaryMixedReformService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 子企业混合所有制改革进展统计表
     */
    @PostMapping("/mixedStatistics")
    public R<ReportReturnVO> mixedStatistics(@Valid @RequestBody(required = false) SubsidiaryMixedReformDTO subsidiaryMixedReformDTO) {
        ReportReturnVO reportReturnVO = subsidiaryMixedReformService.mixedStatistics(subsidiaryMixedReformDTO);
        R<ReportReturnVO> results = new R(CommonCode.SUCCESS);
        results.setPageData(reportReturnVO);
        return results;
    }

    /**
     * 混合所有制企业统计表
     */
    @PostMapping("/enterpriseStatistics")
    public R<ReportReturnVO> enterpriseStatistics(@Valid @RequestBody(required = false) SubsidiaryMixedReformDTO subsidiaryMixedReformDTO) {
        ReportReturnVO reportReturnVO = subsidiaryMixedReformService.enterpriseStatistics(subsidiaryMixedReformDTO);
        R<ReportReturnVO> results = new R(CommonCode.SUCCESS);
        results.setPageData(reportReturnVO);
        return results;
    }

    @PostMapping("/superiorFlag")
    public R<SubsidiaryMixedReformVO> superiorFlag(@RequestBody SubsidiaryMixedReformDTO subsidiaryMixedReformDTO) {
        return R.data(subsidiaryMixedReformService.superiorFlag(subsidiaryMixedReformDTO.getCompanyId()));
    }

    /**
     * 引进民营资本信息情况表
     *
     * @param subsidiaryMixedReformDTO
     * @return
     */
    @PostMapping("/privateCapitalInfoReport")
    public R<ReportReturnVO> privateCapitalInfoReport(@RequestBody SubsidiaryMixedReformDTO subsidiaryMixedReformDTO) {
        ReportReturnVO reportReturnVO = subsidiaryMixedReformService.privateCapitalInfoReport(subsidiaryMixedReformDTO);
        R<ReportReturnVO> results = new R(CommonCode.SUCCESS);
        results.setPageData(reportReturnVO);
        return results;
    }


    @PostMapping("/exportDetailExcel")
    public void exportDetailExcel(@Valid @RequestBody SubsidiaryMixedReform subsidiaryMixedReform, HttpServletResponse response) {
        SubsidiaryMixedReform detail = subsidiaryMixedReformService.getOne(Condition.getQueryWrapper(subsidiaryMixedReform));
        SubsidiaryMixedReformVO subsidiaryMixedReformVO = subsidiaryMixedReformWrapper.entityToVO(detail);
        subsidiaryMixedReformService.exportDetailExcel(subsidiaryMixedReformVO, response);
    }

    /**
     * 混改所有制历史列表
     *
     * @param initialId
     * @return
     */
    @GetMapping("/historyList/{initialId}")
    @ApiOperation(value = "修改记录表", notes = "传入initialId")
    public ListResult<SubsidiaryMixedReformVO> historyList(@PathVariable Long initialId) {
        List<SubsidiaryMixedReform> subsidiaryMixedReformList = subsidiaryMixedReformService.list(Wrappers.<SubsidiaryMixedReform>lambdaQuery()
                .eq(SubsidiaryMixedReform::getInitialId, initialId)
                .eq(SubsidiaryMixedReform::getStatus, FormStatusConstant.FINISH)
                .orderByDesc(SubsidiaryMixedReform::getVersion));
        ListResult<SubsidiaryMixedReformVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(subsidiaryMixedReformWrapper.entityToVO(subsidiaryMixedReformList));
        listResult.setTotal(subsidiaryMixedReformList.size());
        return listResult;
    }

    /**
     * 分页 混改可变更信息列表
     */
    @PostMapping("/adjustableList")
    @ApiOperation(value = "混改可变更信息列表", notes = "传入query")
    public ListResult<SubsidiaryMixedReformVO> adjustableList(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        QueryWrapper<SubsidiaryMixedReform> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new SubsidiaryMixedReform()), entityList
        );
        queryWrapper.lambda().eq(SubsidiaryMixedReform::getCreateCompanyId, TokenUtil.getTokenOrgId());
        queryWrapper.lambda().eq(SubsidiaryMixedReform::getIsLatest, 2);
        queryWrapper.lambda().eq(SubsidiaryMixedReform::getReformStatus, ReformStatus.ADJUSTABLE.getStatus());

        IPage<SubsidiaryMixedReform> pages = subsidiaryMixedReformService.page(Condition.getPage(query), queryWrapper);
        ListResult<SubsidiaryMixedReformVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(subsidiaryMixedReformWrapper.entityToVO(pages.getRecords()));
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());

        return listResult;
    }

    @PostMapping("/latestList")
    @ApiOperation(value = "混改最新信息列表", notes = "传入query")
    public ListResult<SubsidiaryMixedReformVO> latestList(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        QueryWrapper<SubsidiaryMixedReform> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new SubsidiaryMixedReform()), entityList
        );
        queryWrapper.lambda().eq(SubsidiaryMixedReform::getIsLatest, 2);
        queryWrapper.lambda().ne(SubsidiaryMixedReform::getReformStatus, ReformStatus.OUT.getStatus());

        IPage<SubsidiaryMixedReform> pages = subsidiaryMixedReformService.page(Condition.getPage(query), queryWrapper);
        ListResult<SubsidiaryMixedReformVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(subsidiaryMixedReformWrapper.entityToVO(pages.getRecords()));
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());

        return listResult;
    }

}
